#include <iostream>
#include "include/player.h"
#include <netinet/in.h>
#include <errno.h>
#include <string.h>
#include <arpa/inet.h>
#include "include/rapidjson/document.h"

using namespace std;
using namespace rapidjson;


void Player::PlayerInit()
{
    struct sockaddr_in ser_addr;
    struct sockaddr_in cli_addr;

    char msg[200];

    int ser_sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(ser_sockfd<0)
    {
        cout<<"Socker init error: "<<strerror(errno)<<endl;
        exit(1);
    }

    socklen_t addrlen = sizeof(struct sockaddr_in);
    bzero(&ser_addr, addrlen);
    ser_addr.sin_family = AF_INET;
    ser_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    ser_addr.sin_port = htons(8002);
    int error = bind(ser_sockfd, (const sockaddr*)&ser_addr, sizeof(struct sockaddr_in));
    if(error < 0){
        cout << "Bind Error: "<<strerror(errno)<<endl;
        exit(1);
    }

    error = listen(ser_sockfd, 5);
    if(error < 0){
        cout<< "Listen Error: "<<strerror(errno)<<endl;
        close(ser_sockfd);
        exit(1);
    }
    cli_sockfd = accept(ser_sockfd, (sockaddr*)&cli_addr, &addrlen);
    if(cli_sockfd < 0){
        cout<<"Accept Errir: "<<strerror(errno)<<endl;
    }

    while(true){

        size_t recvBytes = recv(cli_sockfd, msg, 200, 0);
        msg[recvBytes] = '\0';

        if(recvBytes>0){
            cout<<"Recevied a connection from "<<inet_ntoa(cli_addr.sin_addr)<<endl;
            Player::Process(string(msg));
        }
    }
    close(ser_sockfd);

}

void Player::PlayBack(std::string file)
{
    string order = "gst-launch-1.0 filesrc location="+file+" ! mad ! alsasink";
    cout<<order<<endl;
    system(order.c_str());
    const int backmsg = 1;
    send(cli_sockfd,&backmsg, sizeof(backmsg),0);
}

void Player::PlayAlert(std::string file)
{
    string order = "gst-launch-1.0 filesrc location="+file+" ! mad ! alsasink";
    cout<<order<<endl;
    system(order.c_str());
    const int backmsg = 2;
    send(cli_sockfd,&backmsg, sizeof(backmsg),0);
}


void Player::Process(std::string json)
{
    Document doc;
    doc.SetObject();
    cout<<json<<endl;

    doc.Parse<0>(json.c_str());

    Value &action = doc["action"];
    string temp(action.GetString());

    if(temp.compare("playback") == 0)
    {
        cout<<action.GetString()<<endl;
        Player::PlayBack(doc["file"].GetString());
    }
    else if(temp.compare("playalert") == 0)
    {
       cout<<action.GetString()<<endl;
       Player::PlayAlert(doc["file"].GetString());
    }
}


Player::Player()
{

}

int main()
{
    Player player;
    player.PlayerInit();
    return 0;
}

